'''
Created on 2011-3-3

@author: jeffrey
'''

from models import *
from google.appengine.ext import db

'''
Common
'''
def getModelList(model=None, filters={}, orderby=None, pagesize=0, pagenum=1):
    if model == None:
        return None
    
    modelList = model.all()
    if filters:
        for filter_key in filters.keys():
            modelList = modelList.filter(filter_key, filters[filter_key])
    
    count = modelList.count()
    
    if orderby:
        modelList = modelList.order(orderby)
    else:
        modelList = modelList.order('-createtime')
    
    if count > 0 and pagesize > 0:
        modelList = modelList.fetch(pagesize, pagesize * (pagenum-1))
    
    if count > 0:
        return modelList
    else:
        return None

'''
1. User Services
'''
def checkUserExistEmail(email, id):
    user_list = getUserList({'email': email})
    if user_list.count() == 0:
        return False
    elif user_list.count() == 1:
        if id and user_list[0].id == id:
            return False
        else:
            return True
    else:
        return True

def getUser(id):
    return User.get_by_id(int(id))

def getUserList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(User, filters, orderby, pagesize, pagenum)

def saveUser(user):
    user.put()
    if not getUserStatisticList({'user': user}):
        us = UserStatistic(user=user, todaypost=0, todayreceive=0, totalpost=0, totalreceive=0)
        saveUserStatistic(us)

def deleteUser(user):
    # Delete the relationship of User and SNS
    deleteUserSNS({'user': user})
    
    # Delete all messages receivers
    messageList = getMessageList({'receiveuser': user})
    if messageList:
        for message in messageList:
            deleteMessage(message)
    
    # Delete all comments of this user
    commentList = getCommentList({'user': user})
    if commentList:
        for comment in commentList:
            deleteComment(comment)
    
    # Delete all tag of this user
    tagList = getTagList({'user': user})
    if tagList:
        for tag in tagList:
            deleteTag(tag)
            
    # Delete the user message statistic data
    userMessageStatisticList = getUserStatisticList({'user': user})
    if userMessageStatisticList:
        for userMessageStatistic in userMessageStatisticList:
            deleteUserStatistic(userMessageStatistic)
    
    # Finally, delete user
    user.delete()

def addUserCredit(user, credit):
    user.credit = user.credit + credit
    saveUser(user)

def getUserGrade(user):
    credit = user.credit
    gradeList = getGradeList(filters={'credit <=': credit}, 
                             orderby='-credit',
                             pagesize=1)
    grade = None
    if gradeList:
        grade = gradeList[0]
    else:
        grade = getGradeList(orderby='credit', pagesize=1)[0]
    return grade

    
'''
2. SNS Services
'''
def getSNS(id):
    return SNS.get_by_id(int(id))

def getSNSList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(SNS, filters, orderby, pagesize, pagenum)

def saveSNS(sns):
    sns.put()

def deleteSNS(sns):
    deleteUserSNS({'sns': sns})
    sns.delete()

'''
3. UserSNS Services
'''
def saveUserSNS(userSNS):
    userSNS.put()

#filter can be user or sns
def deleteUserSNS(filters):
    userSNSList = getUserSNSList(filters)
    if userSNSList:
        for userSNS in userSNSList:
            userSNS.delete()

def getUserSNSList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(UserSNS, filters, orderby, pagesize, pagenum)

'''
4. Message Services
'''
def getMessage(id):
    return Message.get_by_id(int(id))

def deleteMessage(message):    
    deleteMessageTag({'message': message})
        
    commentList = getCommentList({'message': message})
    if commentList:
        for comment in commentList:
            deleteComment(comment)
        
    message.delete()

def getMessageList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(Message, filters, orderby, pagesize, pagenum)

def saveMessage(message):
    message.put()

'''
5. Comment Services
'''
def getComment(id):
    return Comment.get_by_id(int(id))

def deleteComment(comment):
    comment.delete()

def getCommentList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(Comment, filters, orderby, pagesize, pagenum)

def saveComment(comment):
    comment.put()

'''
6. Tag Services
'''
def getTag(id):
    return Tag.get_by_id(int(id))

def deleteTag(tag):
    deleteMessageTag({'tag': tag})
    tag.delete()

def getTagList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(Tag, filters, orderby, pagesize, pagenum)

def saveTag(tag):
    tag.put()
    
'''
7. MessageTag Services
'''
def deleteMessageTag(filters):
    messageTagList = getMessageTagList(filters)
    if messageTagList:
        for messageTag in messageTagList:
            messageTag.delete()

def getMessageTagList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(MessageTag, filters, orderby, pagesize, pagenum)

def saveMessageTag(messageTag):
    messageTag.put()

'''
8. Grade Services
'''
def getGrade(id):
    return Grade.get_by_id(int(id))

def saveGrade(grade):
    grade.put()

def deleteGrade(grade):
    grade.delete()

def getGradeList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(Grade, filters, orderby, pagesize, pagenum)

'''
9. UserStatistic Services
'''
def getUserStatistic(id):
    return UserStatistic.get_by_id(int(id))

def saveUserStatistic(userStatistic):
    userStatistic.put()

def deleteUserStatistic(userStatistic):
    userStatistic.delete()

def getUserStatisticList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(UserStatistic, filters, orderby, pagesize, pagenum)

'''
10. SystemParameter Services
'''
def getSystemParameter(id):
    return SystemParameter.get_by_id(int(id))

def saveSystemParameter(systemParameter):
    systemParameter.put()

def deleteSystemParameter(systemParameter):
    systemParameter.delete()

def getSystemParameterList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(SystemParameter, filters, orderby, pagesize, pagenum)

def getParaValue(pkey, defaultValue=None):
    systemParameterList = getSystemParameterList(filters={'pkey': pkey})
    
    systemParameter = None
    if systemParameterList:
        systemParameter = systemParameterList.get()
    
    value = None
    if systemParameter:
        value = systemParameter.pvalue
    
    if value == None and defaultValue:
        value = defaultValue
    
    return value

'''
11. MessageType Services
'''
def getMessageType(id):
    return MessageType.get_by_id(int(id))

def saveMessageType(messageType):
    messageType.put()

def deleteMessageType(messageType):
    messageList = getMessageList(filters={'messagetype': messageType})
    if messageList:
        for message in messageList:
            message.messagetype=None
            saveMessage(message)
    messageType.delete()

def getMessageTypeList(filters={}, orderby=None, pagesize=0, pagenum=1):
    return getModelList(MessageType, filters, orderby, pagesize, pagenum)
    
